package com.rgs.pay.notify;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.internal.util.AlipaySignature;
import com.rgs.pay.service.SysPayKeyService;
import com.rgs.pay.entity.SysPayKey;
import com.rgs.pay.wechat.util.PayUtil;
import com.rgs.pay.yisheng.util.RsaUtil;
import com.rgs.pay.yisheng.vo.YishengNotifyCommonRespVO;
import com.rgs.pay.yisheng.vo.YishengNotifyScanPayRespVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import static com.rgs.pay.yisheng.util.BasePayUtil.getReqStr;

/**
 * @program: com-rgs-parent
 * @description:
 * @author: Mr.Ren
 * @create: 2022-12-02 13:35
 **/
@RestController
@RequestMapping("/notify")
public class NotifyPayBackController {
    private static final Logger logger = LoggerFactory.getLogger(NotifyPayBackController.class);

    @Resource
    private SysPayKeyService sysPayKeyService;

    /**
     * 微信支付异步回调
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/wx_return")
    public void wxParkingReturn(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("===========================微信回调业务开始=========================");
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader((ServletInputStream) request.getInputStream()));
            String line = null;
            StringBuilder sb = new StringBuilder();
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            br.close();
            //sb为微信返回的xml
            String notityXml = sb.toString();
            String resXml = "";
            System.out.println("接收到的报文：" + notityXml);
            Map params = PayUtil.doXMLParse(notityXml);

            String returnCode = (String) params.get("return_code");
            String attachArr = (String) params.get("attach");
            String[] split = attachArr.split("-");
            Long deptId = Long.valueOf(split[1]);
            if ("SUCCESS".equals(returnCode)) {
                //获取支付配置
                SysPayKey sysPayKey = sysPayKeyService.selectSysPayKeyByDeptId(deptId);
                //验证签名是否正确//回调验签时需要去除sign和空值参数
                Map<String, String> validParams = PayUtil.paraFilter(params);
                //把数组所有元素，按照“参数=参数值”的模式用“&”字符拼接成字符串
                String validStr = PayUtil.createLinkString(validParams);
                //拼装生成服务器端验证的签名
                String sign = PayUtil.sign(validStr, sysPayKey.getWxKey(), "utf-8").toUpperCase();
                if (sign.equals(params.get("sign"))) {
                    //签名成功，开始业务操作 判断订单是否为空或者订单是否已经完成状态修改，已完成修改则返回resXml=null，未完成修改那就完成订单的修改以及自己的业务
                    //resXml = appPayBackService.parkingPayBackByWechat(params);
                } else {
                    System.out.println("微信支付回调失败!签名不一致");
                }
            } else {
                resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
                        + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
            }
            System.out.println(resXml);
            response.setContentType("application/xml");
            BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
            out.write(resXml.getBytes());
            out.flush();
            out.close();
            System.out.println("===========================微信回调业务完成=========================");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 支付宝支付异步回调
     *
     * @param request
     * @return failure失败 success成功
     * @throws Exception
     */
    @RequestMapping("/ali_return")
    public String alipayParkingReturn(HttpServletRequest request) throws Exception {
        System.out.println("===========================支付宝回调业务开始=========================");
        String responseMsg = "failure";
        // 获取支付宝的请求信息
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        if (requestParams.isEmpty()) {
            return "failure";
        }
        // 将 Map<String,String[]> 转为 Map<String,String>
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = iter.next();
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }
        String passBackParams = params.get("passback_params");
        String[] split = passBackParams.split("-");
        Long deptId = Long.valueOf(split[1]);
        SysPayKey sysPayKey = sysPayKeyService.selectSysPayKeyByDeptId(deptId);
        // 验签
        boolean verify = AlipaySignature.rsaCheckV1(params, sysPayKey.getAliPublicKey(), "UTF-8", "RSA2");
        // 验签通过
        if (verify) {
            String trade_status = params.get("trade_status");
            if ("TRADE_SUCCESS".equals(trade_status)) {
                //进入自己的业务 成功返回success
                //responseMsg = appPayBackService.parkingPayBackByAli(params);
            } else {
                responseMsg = "failure";
            }
        } else {
            logger.error("支付宝回调验签失败");
            responseMsg = "failure";
        }

        // }
        System.out.println("===========================支付宝回调业务结束=========================");
        return responseMsg;
    }


    /**
     * 易生支付回调接口
     *
     * @param commonRespVO 回调参数
     * @return error失败 ok成功
     */
    @RequestMapping(value = "/yisheng_parking_return", method = RequestMethod.POST)
    public String yishengParkingReturn(@RequestBody YishengNotifyCommonRespVO commonRespVO) {
        logger.info("rgs-yisheng_parking_return方法");
        System.out.println("===========================易生回调业务开始=========================");
        System.out.println("返回对象:" + commonRespVO);
        try {
            //先判断系统返回码是否正常在开始业务操作
            if (StrUtil.equals(commonRespVO.getSysRetcode(), "000000")) {
                //获取自定义信息
                String orgInfo = commonRespVO.getOrgInfo();
                String[] split = orgInfo.split("-");
                Long deptId = Long.valueOf(split[1]);
                SysPayKey sysPayKey = sysPayKeyService.selectSysPayKeyByDeptId(deptId);
                //获取data
                YishengNotifyScanPayRespVO data = commonRespVO.getData();
                //验签
                JSONObject responseData = (JSONObject) JSONObject.toJSON(data);
                boolean verifyFlag = RsaUtil.verifyBySHA256WithRSA(getReqStr(responseData), commonRespVO.getSign(), sysPayKey.getAliPublicKey());

                if (verifyFlag) {

                    if (StrUtil.equals(data.getFinRetcode(), "00")) {
                        //业务处理
                        //oriOrgTrace 订单号 交易流水
                        //return appPayBackService.parkingPayBackByYisheng(commonRespVO);
                        return "ok";
                    } else {
                        logger.error("回调交易失败，finRetcode" + data.getFinRetcode());
                        return "error";
                    }
                } else {
                    //验签失败
                    logger.error("易生回调验签失败");
                    return "error";
                }
            } else {
                logger.error("易生回调交易失败，sysRetcode" + commonRespVO.getSysRetcode());
                return "error";
            }
        } catch (Exception e) {
            logger.error("易生回调异常");
            e.printStackTrace();
            return "error";
        }
    }
}
